// pages/search/search.js
let {getHotsong,getSongs} = require("../../api/search");
Page({

  data: {
    hotList:[],
    keywords:"",
    resultList:[]
  },

  keywords(e){
    let aaa = e.detail.value;
    this.setData({
      keywords:aaa
    },()=>{
      this.getSong()
    })
  },

  async onLoad(options){
    //用来请求热门歌曲
    let id = this.data.initial;
    let res = await getHotsong(id);
    console.log(res);

    this.setData({
      hotList:res.data.result.hots,
      
    })
  },
  
  getSong(){
    if(this.data.keywords == ""){
 
      this.setData({
        resultList:[]
      })
    }else{
      getSongs(this.data.keywords).then(res=>{
        console.log(res);
        this.setData({
          resultList:res.data.result.songs
        })
      })
    }
  },

  hotSear(e){
    console.log(e.currentTarget.dataset.songname)
    this.setData({
      keywords:e.currentTarget.dataset.songname
    },()=>{
      this.getSong()
    })
  },

  goPlay(e){
    //获得搜索结果列表中选中的id
   console.log(e.currentTarget.dataset.id);
    let musicid=e.currentTarget.dataset.id.id
    let musicname=e.currentTarget.dataset.id.name
    let songer=e.currentTarget.dataset.id.artists[0].name
    let musicimg=e.currentTarget.dataset.id.artists[0].img1v1Url
    //造相同数据类型
    let obj={
       name:musicname,
       id:musicid,
       ar:[{name:songer}],
       al: {picUrl:musicimg}
   }
   //获取本地储存
   let playList= wx.getStorageSync('playList');
   if(playList){
       playList.unshift(obj);
       console.log(playList);
       //再次存储
       wx.setStorage({
           data: playList,
           key:'playList',
           //成功跳转到正在播放页面
           success(){
               wx.reLaunch({
                   url: `/pages/plays/plays?index=0`,
                 })
           }
       })
   }else{
       let playList=[];
       playList.unshift(obj);
       wx.setStorage({
           data: playList,
           key:'playList',
           //成功跳转到正在播放页面
           success(){
               wx.reLaunch({
                   url: `/pages/plays/plays?index=0`,
                 })
           }
       })
   }
}
})

